package com.bzsg.simpleMediaPlayer.viewModel

import android.content.Context
import android.graphics.Bitmap
import androidx.lifecycle.ViewModel
import com.bzsg.simpleMediaPlayer.extend.requestIO
import com.bzsg.simpleMediaPlayer.repository.VideoRepository
import com.bzsg.simpleMediaPlayer.data.VideoItem
import com.bzsg.simpleMediaPlayer.data.VideoUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

@HiltViewModel
class VideoViewModel
    @Inject
    constructor(
        @ApplicationContext private val context: Context,
        private val videoRepository: VideoRepository,
    ) : ViewModel() {
        // UI 状态定义
        private val _uiState = MutableStateFlow<VideoUiState>(VideoUiState.Loading)
        val uiState: StateFlow<VideoUiState> = _uiState.asStateFlow()

        // 加载视频数据
        fun loadVideos() {
            requestIO {
                _uiState.value = VideoUiState.Loading
                try {
                    val videos = videoRepository.getVideos()
                    val maps = loadFirstScreenThumbnails(videos)
                    _uiState.value = VideoUiState.Success(videos, maps)
                } catch (e: Exception) {
                    _uiState.value = VideoUiState.Error(e.message ?: "Unknown error")
                }
            }
        }

        // 预加载首屏缩略图
        private suspend fun loadFirstScreenThumbnails(items: List<VideoItem>): Map<Long, Bitmap> =
            coroutineScope {
                val firstScreenItems = items.take(12)
                val deferredMap =
                    firstScreenItems.associate { item ->
                        item.id to
                            async(Dispatchers.IO) {
                                videoRepository.generate(context, item.id)
                            }
                    }
                // 正确等待并过滤结果
                deferredMap.map { (id, deferred) ->
                    id to deferred.await()
                }.filter { (_, bitmap) ->
                    bitmap != null
                }.associate { (id, bitmap) ->
                    id to bitmap!!
                }
            }

        // 按需加载单个缩略图
        suspend fun loadThumbnail(
            context: Context,
            mediaId: Long,
        ): Bitmap? {
            return videoRepository.generate(context, mediaId)
        }
    }
